﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using S.Common.EditReproductivePresenceStateHelper;
using S.Common.EditWanderStateHelper;
using S.Common.helper;
using S.Parturition.API.Application.Command;
using S.Parturition.API.Dto;
using S.Parturition.Domain;
using S.Parturition.Domain.Model;
using S.Parturition.Infrastructure.Interface;

namespace S.Parturition.API.Application.CommandHandlers
{
    public class AddParturitionHandler : IRequestHandler<AddParturitionCommand, bool>
    {

        private readonly IParturitionRepository parturition;

        private readonly IMapper mapper;

        private readonly MyDbContext dbContext;

        private readonly IHttpContextAccessor httpContextAccessor;

        private readonly IConfiguration configuration;

        public AddParturitionHandler(IParturitionRepository parturition, IMapper mapper, MyDbContext dbContext, IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            this.parturition = parturition;
            this.mapper = mapper;
            this.dbContext = dbContext;
            this.httpContextAccessor = httpContextAccessor;
            this.configuration = configuration;
        }


        public async Task<bool> Handle(AddParturitionCommand request, CancellationToken cancellationToken)
        {

            //使用事物
            using (var tran = dbContext.Database.BeginTransaction())
            {
                try
                {
                    string Gateway = configuration.GetValue<string>("Gateway");

                    #region 添加分娩信息
                    //使用automapper传值
                    var ParturitionModel = mapper.Map<ParturitionModel>(request.addParturitionDto);
                    ParturitionModel.CreateDate = DateTime.Now;    //创建时间赋值为当前时间
                    ParturitionModel.UpdateDate = null;            //修改时间赋值为空
                    ParturitionModel.AuditTime = null;             //审核时间赋值为空

                    //执行添加分娩方法
                    await parturition.AddAsync(ParturitionModel);

                    #endregion

                    #region 反填并修改种母历史记录

                    request.editBreed.EarTag = ParturitionModel.EarTag;

                    //反填种母历史记录
                    var jsonString = HttpClientHelper.PostResponseKey($"{Gateway}/bhread/api/BreedingHistoryRead/GetNewBreedingHistoryByPId", request.editBreed);
                    //将获取到的种母历史记录序列化
                    var response = JsonConvert.DeserializeObject<BreedingHistoryDto>(jsonString);

                    if (string.IsNullOrWhiteSpace(jsonString))
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    //修改分娩的信息
                    response.DeliveryDate = ParturitionModel.DeliveryDate;
                    response.CurrentPregnancy++;
                    response.IsEditor = true;

                    //修改种母历史记录
                    var breeding = HttpClientHelper.PutDataResponse($"{Gateway}/bhset/api/BreedHistory/UpdateBreedingHistory", response);

                    if (breeding == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion

                    #region 添加转舍信息

                    request.transferDto.EarTag = ParturitionModel.EarTag;
                    request.transferDto.SurrenderDate = ParturitionModel.DeliveryDate; //转舍时间为分娩时间
                    //跨服务调用添加转舍接口
                    var transfer = HttpClientHelper.PostResponse($"{Gateway}/transset/api/TransFer/CreateSheepTransFer", request.transferDto);

                    if (transfer == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion

                    #region 修改档案信息

                    var archives = EditReproductivePresenceState.UpdateReproductivePresenceState(ParturitionModel.EarTag, 1, 8, ParturitionModel.DeliveryDate, Gateway);

                    if (archives == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }
                    #endregion

                    #region 修改流转状态

                    EditWanderState.EditWander(ParturitionModel.EarTag, 4, Gateway);

                    #endregion

                    #region 添加生产记录

                    //WanderCreateDto wander = new WanderCreateDto
                    //{
                    //    WanderId = 0,
                    //    EarTag = ParturitionModel.EarTag,
                    //    WanderReproductiveState = (WanderReproductiveStateEnum)4,
                    //    Content = "健羔：0，弱羔：0，畸形：0，死胎：0，木乃伊：0，畸胎：0，窝重：0.00",
                    //    WanderDate = ParturitionModel.DeliveryDate,
                    //    SerialNumber = ParturitionModel.SerialNumber,
                    //};

                    //var wand = HttpClientHelper.PostResponse($"{Gateway}/achs/api/Wander/WanderCreate", wander);

                    //if (wand == "0")
                    //{
                    //    //事物回滚
                    //    tran.Rollback();
                    //    return false;
                    //}

                    #endregion

                    #region 修改妊检表状态

                    var pregnancytest = HttpClientHelper.PostResponse($"{Gateway}/PregnancySet/api/PregnancyTest/UpdateSheepState?EarTag=" + ParturitionModel.EarTag + "", "");

                    if (pregnancytest == "0")
                    {
                        //事物回滚
                        tran.Rollback();
                        return false;
                    }

                    #endregion


                    //事物执行
                    tran.Commit();

                    return true;
                }
                catch (Exception)
                {
                    //事物回滚
                    tran.Rollback();

                    return false;
                }
            }

        }
    }
}
